package cn.bj.yu.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author 周宇
 * @create 2020-08-17 0:39
 * ABA 问题的解决 AtomicStampedReference
 * 注意变量版本号修改和获取问题。不要写错
 */
public class ABADemo2 {

    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();//获得版本号
            System.out.println("T1 stamp 01=>" + stamp);
            // 暂停1秒钟，保证下面线程获得初始版本号
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("T1 stamp 02=>" + atomicStampedReference.getStamp());

            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("T1 stamp 03=>" + atomicStampedReference.getStamp());

        }, "T1").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();//获得版本号
            System.out.println("T2 stamp 01=>" + stamp);
            // 暂停3秒钟，保证上面线程先执行
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            boolean result = atomicStampedReference.compareAndSet(100, 2020, stamp, stamp + 1);
            System.out.println("T2 是否修改成功 =>" + result);
            System.out.println("T2 最新stamp =>" + atomicStampedReference.getStamp());
            System.out.println("T2 当前的最新值 =>" + atomicStampedReference.getReference());
        }, "T2").start();
    }
}